<template name="eagle-input">
    <div class="eagle-input">
        <van-cell v-if="multiRow" :title="title" :required="isMust"></van-cell>
        <!-- <van-skeleton v-if="novalue" :row="2"></van-skeleton> -->
        <van-field  v-model="inputValue" :value="value" :label="label" :placeholder="placeholder" :required="required" :left-icon="leftIcon" :right-icon="rightIcon" :rules="rulesArray" :readonly="readonly" :name="name" :type="type" :rows="rows" :autosize="autosize" :border="border" :input-align="inputalign" :error-message="errorMessage" :label-width="labelWidth" :clearable="clearable" :clickable="clickable" v-bind:class="{ eagle_input_text : (isInputText && isCustom), eagle_feild_text:(!isInputText && isCustom)}" @click="click" @click-input="clickInput" @keypress="keypress">
            <template #right-icon>
                <van-icon name="arrow" v-if="islink" />
                <van-icon name="scan" v-if="isScan" @click="scan()" />
            </template>

            <template #input>
                <slot name="input"></slot>
            </template>
            <template #button>
                <slot name="button"></slot>
            </template>
            <template #extra>
                <slot name="extra"></slot>
            </template>

            <slot></slot>
        </van-field>
        <slot name="gg"></slot>
    </div>
</template>
<script>
import { is_weixin } from "@/utils/common.js";
import os from "@/utils/os.js";
import { loadWxTicket, loadWxWorkTicket } from "@/utils/Ticket.js";
export default {
    name: "eagle-input",
    props: {
        name: {
            type: [String],
            default: "",
        },
        value: {
            type: [String, Number],
            default: "",
        },
        maxlength: {
            type: [Number, String],
            default: -1,
        },
        label: {
            type: [String],
            default: "",
        },
        required: {
            type: [Boolean],
            default() {
                return false;
            },
        },
        labelWidth: {
            type: [Number, String],
            default: "100px",
        },
        type: {
            type: String,
            default: "text",
        },
        placeholder: {
            type: String,
            default: "",
        },
        labelalign: {
            type: String,
            default: "left",
        },
        islink: {
            type: [Boolean],
            default() {
                return false;
            },
        },
        leftIcon: {
            type: String,
            default: "",
        },
        rightIcon: {
            type: String,
            default: "",
        },
        //是否自适应内容高度，只对 textarea 有效,单位为px
        autosize: {
            type: [Boolean],
            default() {
                return false;
            },
        },
        rules: {
            type: Array,
            default() {
                return [];
            },
        },
        readonly: {
            type: [Boolean],
            default() {
                return false;
            },
        },
        isInputText: {
            type: [Boolean],
            default() {
                return false;
            },
        },
        multiRow: {
            type: [Boolean],
            default() {
                return false;
            },
        },
        title: {
            type: String,
            default: "",
        },
        rows: {
            type: [String, Number],
            default: "2",
        },
        border: {
            type: [Boolean],
            default() {
                return false;
            },
        },
        inputalign: {
            type: String,
            default: "left",
        },
        errorMessage: {
            type: String,
            default: "",
        },
        requiredReadonly: {
            type: Boolean,
            default: () => false,
        },
        isCustom: {
            type: Boolean,
            default: () => true,
        },
        isMust: {
            type: Boolean,
            default: () => false,
        },
        clearable: {
            type: Boolean,
            default: () => false,
        },
        clickable: {
            type: Boolean,
            default: () => false,
        },

        isScan: {
            type: [Boolean],
            default() {
                return false;
            },
        },
    },
    data() {
        return {
            inputValue: this.value,
            result: "",
            novalue:true
        };
    },
    created() { },
    computed: {
        rulesArray: function () {
            let array = [];
            if (this.rules && this.rules.length > 0) {
                array = this.rules;
            } else {
                if (this.required && !this.requiredReadonly) {
                    array.push({
                        required: true,
                        message: "请输入" + (this.label ? this.label : ""),
                    });
                }
            }
            return array;
        },
    },
    watch: {
        value(newvalue, oldvalue) {
            this.inputValue = this.value;
            console.log(newvalue, oldvalue)
            this.novalue=false
        },
        inputValue(val) {
            //当数据变化，组件model的双向绑定
            this.$emit("input", val);
        },
    },

    mounted() {
        if (this.isScan) {
            if (!os.isPC && os.isWxWork) {
                console.log("企业微信客户端");
                loadWxWorkTicket(["scanQRCode"]);
            } else if (!os.isPC && os.isWx) {
                console.log("微信客户端");
                this.getSign(["scanQRCode"]);
            } else {
                console.log("其他");
                // this.getSign(["scanQRCode"]);
            }
            window.scanResult = this.scanResult;
            // 页面加载完成唤醒微信扫一扫
        }
    },

    methods: {
        click() {
            this.$emit("click");
        },
        clickInput() {
            this.$emit("click-input");
        },
        //扫描二维码
        scan() {
            // 安卓
            if (window.jsListener) {
                window.jsListener.Scan();
            }

            //ios 交互 微信也有交互 多做判断
            if (is_weixin()) {
                //如果是微信执行的操作

                var ua = navigator.userAgent.toLowerCase();
                if (ua.match(/wxwork/i) == "wxwork") {
                    //企业微信
                    this.onscanQY();
                }
                else if (ua.match(/MicroMessenger/i) == "micromessenger") {
                    //微信
                    this.onscan();
                }
            } else {
                //如果不是微信执行的操作
                if (window.webkit) {
                    if (window.webkit.messageHandlers) {
                        if (window.webkit.messageHandlers.Scan) {
                            window.webkit.messageHandlers.Scan.postMessage("");
                        }
                    }
                }
            }
        },
        scanResult(strings) {
            let parent = this.$parent;
            let count = 0;
            while (parent && !parent.scanresultcallback && count < 10) {
                parent = parent.$parent;
                count++;
            }
            parent.scanresultcallback(strings);
        },

        onscanQY() {
            let _this = this;
            wx.invoke(
                "scanQRCode",
                {
                    desc: "scanQRCode desc",
                    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                },
                (res) => {
                    if (res.err_msg == "scanQRCode:ok") {
                        if (res.resultStr) {
                            let qrCode = os.isAndroid
                                ? res.resultStr
                                : os.isPhone
                                    ? JSON.parse(res.resultStr).scan_code.scan_result
                                    : "";

                            console.log(qrCode);
                            setTimeout(() => {
                                _this.callback(qrCode);
                            }, 300);
                        }
                    }
                }
            );
        },

        callback(str) {
            this.scanResult(str);
            // this.$parent.scanresultcallback(str);
        },

        onscan() {
            console.log("进入扫描方法");
            let _this = this;
            wx.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success: function (res) {
                    console.log("扫描成功");

                    if (res.resultStr) {
                        console.log(res.resultStr);

                        setTimeout(() => {
                            _this.callback(res.resultStr);
                        }, 300);
                    } else {
                        Toast.fail("无效的二维码");
                    }
                },
                error: function (res) {
                    Toast("出错了");
                },
            });

            // wx.ready(function() {
            // 	console.log("开始扫描")
            // 	wx.scanQRCode({
            // 	needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
            // 	scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
            // 	success: function(res) {
            // 		console.log("扫描成功")

            // 		if (res.resultStr) {
            // 			console.log(res.resultStr)
            // 			_this.callback(res.resultStr);
            // 		} else {
            // 			Toast.fail("无效的二维码");
            // 		}
            // 	},
            // 	error: function(res) {
            // 		Toast("出错了");
            // 	},
            // 	});
            // });
        },
        getSign(arr) {
            let params = {
                url: window.location.href.split("#")[0],
            };
            this.$axios
                .get("/WxOpen/GetSignature", { params: params })
                .then((res) => {
                    console.log("调用成功");
                    wx.config({
                        beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: res.data.appId, // 必填，公众号的唯一标识
                        timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                        nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                        signature: res.data.signature, // 必填，签名，见附录1
                        jsApiList: arr, // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                    });
                    wx.ready(() => {
                        wx.checkJsApi({
                            jsApiList: arr, // 需要检测的JS接口列表，所有JS接口列表见附录2,
                            success: function (res) {
                                arr.forEach((a) => {
                                    console.log(
                                        "调用JS方法[" +
                                        a +
                                        "]的微信tick成功！" +
                                        JSON.stringify(res)
                                    );
                                });
                            },
                        });
                    });
                    wx.error((err) => {
                        console.log("错误" + err);
                    });
                });
        },
        keypress(val) {
            this.$emit("keypress", val);
        },
    },
};
</script>

<style lang="less" scoped>
/deep/ .van-cell {
    position: static;
    color: #646566;
}

@field-text-area-min-height: 30px;

/deep/ .van-divider {
    margin: 0.001rem 2rem;
}

.eagle-input {
    position: relative;
}
.eagle-input::after {
    position: absolute;
    box-sizing: border-box;
    content: " ";
    pointer-events: none;
    right: 0.42667rem;
    bottom: 0;
    left: 0.42667rem;
    border-bottom: 0.02667rem solid #ebedf0;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
}
</style>
